package site.wanjiahao.app;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import site.wanjiahao.handler.server.*;
import site.wanjiahao.protocol.BasedFrameDecoder;
import site.wanjiahao.protocol.MessageCodec;

@Slf4j
public class Server {

    public static void main(String[] args) {
        // 接受线程
        NioEventLoopGroup boss = new NioEventLoopGroup(1);
        // 工作线程
        NioEventLoopGroup works = new NioEventLoopGroup(8);
        MessageCodec messageCodec = new MessageCodec();
        LoggingHandler loggingHandler = new LoggingHandler(LogLevel.DEBUG);
        IdleStateHandler idleStateHandler = new IdleStateHandler(5, 0, 0);
        MyChannelDuplexHandler myChannelDuplexHandler = new MyChannelDuplexHandler();
        PingMessageHandler pingMessageHandler = new PingMessageHandler();
        RpcRequestMessageHandler rpcRequestMessageHandler = new RpcRequestMessageHandler();
        ClientClosingHandler clientClosingHandler = new ClientClosingHandler();

        new ServerBootstrap()
                .group(works, boss)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) {
                        ch.pipeline()
                                .addLast(loggingHandler)
                                .addLast(new BasedFrameDecoder())
                                .addLast(messageCodec)
                                .addLast(idleStateHandler)
                                .addLast(myChannelDuplexHandler)
                                .addLast(pingMessageHandler)
                                .addLast(rpcRequestMessageHandler)
                                .addLast(clientClosingHandler);
                    }

                })
                .bind(8080);

    }

}
